package edu.hebtu.util;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import java.util.Calendar;
import java.util.Date;

public class autoIdUtil {
    public static String autoId(String id, String head) {
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        final int first = 1;          //字符串中日期标志的开始位置
        now.setTime(date);
        // 将时分秒,毫秒域清零
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        now.set(Calendar.MILLISECOND, 0);
        if (id == null || id.length() < 11)
            return head + String.valueOf(now.get(Calendar.YEAR)).substring(2, 4) + String.format("%02d", now.get(Calendar.MONTH) + 1) +
                    String.format("%02d", now.get(Calendar.DATE)) + "0001";
        int year = Integer.parseInt("20" + id.substring(first, first + 2));
        int month = Integer.parseInt(id.substring(first + 2, first + 4)) - 1;
        int day = Integer.parseInt(id.substring(first + 4, first + 6));
        Calendar idDate = Calendar.getInstance();
        idDate.set(year, month, day, 0, 0, 0); //年月日
        LocalDate ld1 = new LocalDate(new DateTime(now.getTime()));
        LocalDate ld2 = new LocalDate(new DateTime(idDate.getTime()));
        System.out.println("now=" + now.getTime() + "  id=" + idDate.getTime()
                                + "   equals?" + ld1.equals(ld2));
        if (ld1.equals(ld2)) {
            return id.substring(0, first + 6) + String.format("%04d", Integer.parseInt(id.substring(first + 6)) + 1);
        } else {
            return head + String.valueOf(now.get(Calendar.YEAR)).substring(2, 4) + String.format("%02d", now.get(Calendar.MONTH) + 1) +
                    String.format("%02d", now.get(Calendar.DATE)) + "0001";
        }
    }
}
